<template>
    <view class="container">
        <NavBar title="审批" />
        <scroll-view class="list" scroll-y>
            <view class="list-item">
                <view class="item-title">
                    审配意见
                </view>
                <view class="item-content select">
                    <view class="pass " @click="setSelect('pass')">
                        <view :class="{ 'unselected': !isPass }">
                            通过
                        </view>
                        <view class="select-icon" v-show="isPass">
                            <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
                                fill="none" version="1.1" width="15.909899711608887" height="11.195899963378906"
                                viewBox="0 0 15.909899711608887 11.195899963378906">
                                <g>
                                    <path
                                        d="M5.89254,8.83885C5.89254,8.83885,14.7314,0,14.7314,0C14.7314,0,15.9099,1.17852,15.9099,1.17852C15.9099,1.17852,5.89254,11.1959,5.89254,11.1959C5.89254,11.1959,0,5.3033,0,5.3033C0,5.3033,1.17851,4.1248,1.17851,4.1248C1.17851,4.1248,5.89254,8.83885,5.89254,8.83885C5.89254,8.83885,5.89254,8.83885,5.89254,8.83885Z"
                                        fill-rule="evenodd" fill="#165DFF" fill-opacity="1" />
                                </g>
                            </svg>
                        </view>
                    </view>
                    <view class="pass" @click="setSelect('noPass')">
                        <view :class="{ 'unselected': isPass }">
                            不通过
                        </view>
                        <view class="select-icon" v-show="!isPass">
                            <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
                                fill="none" version="1.1" width="15.909899711608887" height="11.195899963378906"
                                viewBox="0 0 15.909899711608887 11.195899963378906">
                                <g>
                                    <path
                                        d="M5.89254,8.83885C5.89254,8.83885,14.7314,0,14.7314,0C14.7314,0,15.9099,1.17852,15.9099,1.17852C15.9099,1.17852,5.89254,11.1959,5.89254,11.1959C5.89254,11.1959,0,5.3033,0,5.3033C0,5.3033,1.17851,4.1248,1.17851,4.1248C1.17851,4.1248,5.89254,8.83885,5.89254,8.83885C5.89254,8.83885,5.89254,8.83885,5.89254,8.83885Z"
                                        fill-rule="evenodd" fill="#165DFF" fill-opacity="1" />
                                </g>
                            </svg>
                        </view>

                    </view>
                </view>
            </view>
            <view class="list-item" v-if="revokeShow">
                <view class="item-title">
                    撤回位置
                </view>

                <view class="item-content pselect" :class="{ 'unselected': !selectedOutOption }"
                    @click="handleOutClick">
                    {{ selectedOutOption ? selectedOutOption : '请选择' }}
                </view>
            </view>
            <view class="list-item">
                <view class="item-title opinion">
                    {{ userInfo.dept.deptName }}意见
                </view>
            </view>
            <uv-textarea class="textarea textareaStyle" maxlength='100' v-model="remarks" count
                placeholder="请输入内容"></uv-textarea>
            <view class="list-item">
                <view class="item-title">
                    手写签名
                </view>
            </view>
            <view style="width: 750rpx ;height: 456rpx;background-color: #fff;">
                <l-signature disableScroll ref="signatureRef" :penColor="penColor" :penSize="penSize"></l-signature>
            </view>
            <uv-button class="but" shape="circle" type="primary" text="清空签名" @click="onClick('clear')"></uv-button>
            <uv-button class="but" shape="circle" type="primary" text="提交" @click="onClick('save')"></uv-button>
            <view v-if="showOutPicker" class="picker-container">
                <view class="picker-mask" @click="closeOutPicker"></view>
                <view class="picker-content">
                    <view class="picker-header">
                        <text class="picker-cancel" @click="closeOutPicker">取消</text>
                        <text class="picker-title"></text>
                        <text class="picker-confirm" @click="confirmOut">确定</text>
                    </view>
                    <scroll-view scroll-y class="picker-list">
                        <view class="picker-item" v-for="(item, index) in outOptions" :key="index"
                            :class="{ 'selected': selectedOutOption === item.name }" @click="selectOutOption(item)">
                            <text>{{ item.name }}</text>
                        </view>
                    </scroll-view>
                </view>
            </view>
        </scroll-view>
    </view>

</template>

<script>
import NavBar from '@/components/NavBar/index.vue'
import { getRevike, confirmExamine } from '@/utils/app.js'
import { useUserStore } from '@/store/index.js'
import { storeToRefs } from 'pinia'
import { BASEURL } from '@/utils/request.js'
export default {
    components: { NavBar },
    setup() {
        const userStore = useUserStore()
        const { userInfo } = storeToRefs(userStore)

        return {
            userInfo,
            BASEURL
        }
    },
    data() {
        return {
            remarks: '',
            penColor: '#000',
            penSize: 3,
            url: '',
            urlAddress: '',
            openSmooth: true,
            isPass: true,
            outOptions: [],
            selectedOutOption: '',
            showOutPicker: false,
            revokeShow: false,
            parsedData: {},
            selectedOutOptionId: ''
        };
    },
    onLoad(options) {
        this.parsedData = JSON.parse(decodeURIComponent(options.data))
        this.getTuiHuiDataList()
    },
    methods: {
        onPullDownRefresh() {
            this.getTuiHuiDataList()
        },
        //获取审批列表
        getTuiHuiDataList() {
            getRevike({ approveId: this.parsedData.approveId }).then(res => {
                if (res && res.code == 200) {
                    this.outOptions = res.data
                }
            })
        },
        handleOutClick() {
            // this.$refs.popup.open()
            this.showOutPicker = true
        },
        setSelect(val) {
            this.isPass = !this.isPass;
            this.revokeShow = val !== 'pass';
        },
        closeOutPicker() {
            this.showOutPicker = false;
            this.selectedOutOption = '';
        },
        confirmOut() {
            this.showOutPicker = false;
        },
        selectOutOption(value) {
            this.selectedOutOption = value.name;
            this.selectedOutOptionId = value.id;
        },
        onClick(type) {

            if (type == 'openSmooth') {
                this.openSmooth = !this.openSmooth
                return
            }
            if (type == 'save') {
                // 检查撤回位置是否选择
                if (this.revokeShow && !this.selectedOutOption) {
                    uni.showToast({
                        title: '请选择撤回位置',
                        icon: 'none'
                    })
                    return
                }
                // 检查签名组件是否存在
                if (!this.$refs.signatureRef) {
                    uni.showToast({
                        title: '签名组件未初始化',
                        icon: 'none'
                    })
                    return
                }

                this.$refs.signatureRef.canvasToTempFilePath({
                    success: (res) => {

                        // 检查是否为空画板
                        if (res.isEmpty) {
                            uni.showToast({
                                title: '请先进行签名',
                                icon: 'none'
                            })
                            return
                        }

                        let that = this
                        this.url = res.tempFilePath

                        // 先上传签名到服务器
                        this.uploadSignature(res.tempFilePath)
                    },
                    fail: (err) => {
                        uni.showToast({
                            title: '签名生成失败',
                            icon: 'none'
                        })
                    }
                })
                return
            }
            if (this.$refs.signatureRef)
                this.$refs.signatureRef[type]()
        },

        // 处理签名成功
        handleSignatureSuccess() {
            uni.showToast({
                title: '保存成功',
                icon: 'none'
            })

            // 准备提交数据
            const userStore = useUserStore()
            let data = {
                projectId: this.parsedData.projectId,
                contractId: this.parsedData.contractId,
                flowType: this.parsedData.flowType,
                approveId: this.parsedData.approveId,
                relatedId: this.parsedData.relatedId,
                userId: this.userInfo.userId,
                status: this.isPass ? 1 : 2,
                autograph: this.urlAddress,
                nextManageItemId: this.isPass ? '' : this.selectedOutOptionId,
                remarks: this.remarks
            }

            // 调用审批接口
            confirmExamine(data).then(res => {
                if (res && res.code === 200) {
                    uni.showToast({
                        title: '审批提交成功',
                        icon: 'success'
                    })
                    setTimeout(() => {
                        uni.navigateBack({
                            url: 'pages/approval/index'
                        })
                    }, 1000)
                } else {
                    uni.showToast({
                        title: res?.message || '审批提交失败',
                        icon: 'none'
                    })
                }
            }).catch(err => {
                uni.showToast({
                    title: '网络错误，请重试',
                    icon: 'none'
                })
            })
        },
        // 上传签名到服务器
        uploadSignature(tempFilePath) {
            uni.showLoading({
                title: '上传签名中...'
            })

            // 获取token
            const token = uni.getStorageSync("token");
            uni.uploadFile({
                url: `${BASEURL}/common/upload`, // 使用项目中的实际上传地址
                filePath: tempFilePath,
                name: 'file',
                header: {
                    'Authorization': token
                },
                formData: {
                    type: 'signature',
                    userId: this.userInfo.userId
                },
                success: (res) => {
                    uni.hideLoading()

                    try {
                        const data = JSON.parse(res.data)
                        if (data.code === 200) {
                            // 上传成功，保存返回的文件路径
                            this.urlAddress = data.annexUrl

                            // 继续处理审批提交
                            this.handleSignatureSuccess()
                        } else {
                            uni.showToast({
                                title: data.message || '签名上传失败',
                                icon: 'none'
                            })
                        }
                    } catch (error) {
                        uni.showToast({
                            title: '签名上传失败',
                            icon: 'none'
                        })
                    }
                },
                fail: (err) => {
                    uni.hideLoading()
                    uni.showToast({
                        title: '签名上传失败',
                        icon: 'none'
                    })
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.list {
    height: 1450rpx;

    .list-item {
        display: flex;
        padding: 32rpx;
        border-bottom: 1rpx solid #E7E7E7;
        font-size: 32rpx;

        .item-title {
            padding-right: 10rpx;
            width: 162rpx;
            text-align: right;
        }

        .opinion {
            padding-left: 30rpx;
            width: auto;
        }

        .select {
            flex: 1;
            display: flex;
            justify-content: space-between;
        }
    }

    .item-content {
        display: flex;

        .pass {
            width: 200rpx;
            display: flex;
            justify-content: space-around;
        }

    }

    .unselected {
        color: rgba(0, 0, 0, 0.25);
    }

    .pselect {
        padding-left: 60rpx;
    }

    .textarea {
        height: 248rpx;
    }

    .textareaStyle {
        padding: 10rpx 60rpx !important;
    }

    .but {
        width: 540rpx;
        height: 90rpx;
        margin: 0 auto;
    }
}

/* 修改底部弹出层部分 */
.picker-container {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    z-index: 100;
}

.picker-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.4);
}

.picker-content {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #FFFFFF;
    border-top-left-radius: 16px;
    border-top-right-radius: 16px;
}

.picker-header {
    display: flex;
    height: 53px;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 0 16px;
    border-bottom-width: 1px;
    border-bottom-color: #EEF2F9;
    margin-bottom: 30rpx;
}

.picker-title {
    font-size: 16px;
    color: #1D2129;
    font-weight: 400;
}

.picker-cancel,
.picker-confirm {
    font-size: 16px;
}

.picker-cancel {
    color: #86909C;
}

.picker-confirm {
    color: #165DFF;
}

.picker-list {
    padding: 24rpx 0;
    max-height: 350rpx;
    /* overflow: scroll; */
}

.picker-item {
    display: flex;
    height: 44px;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    padding: 0 16px;
}

.picker-item text {
    font-size: 16px;
    color: #1D2129;
}

/* 移除选中状态相关样式 */
.selected-icon {
    display: none;
}
</style>
